/*
 *
 *  Copyright (C) 2010 GSyC/LibreSoft, Universidad Rey Juan Carlos.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Raúl Román López <rroman@gsyc.es>
 *
 */
package com.LibreGeoSocial.App.OMFActivity;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.LibreGeoSocial.App.R;
import com.LibreGeoSocial.App.OMF.Copiagenda;
import com.LibreGeoSocial.App.OMF.OMFManager;

public class PhonesList extends ListActivity{
	private static final int DIALOG_WELCOME = 1;
	private static final int DIALOG_SEARCH = 2;
	private static final String MOBILE_PHONE = "phone";
	
	private static final int MENU_FIND = Menu.FIRST + 1;
	
	CopiagendaAdapter mAdapter;
	
	private static List<String> contactlist;
	
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		showDialog(DIALOG_WELCOME);
		
  		// Adapter for ListView
//        mAdapter = new PlacesAdapter(this);
//        setListAdapter(mAdapter);

		
	}
	
	public static List<String> getList(){
		return contactlist;
	}
	
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	
        Intent resultIntent = new Intent();
        
        if(contactlist!=null)
        	resultIntent.putExtra(MOBILE_PHONE, contactlist.get(position).replaceAll("\"", "").split(",")[18]);
        else
        	resultIntent.putExtra(MOBILE_PHONE, "");
        
        setResult(Activity.RESULT_OK, resultIntent);
        finish();
    
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_FIND, 0, "Find")
				.setIcon(R.drawable.magnif)
				.setAlphabeticShortcut('F');
                
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item) {
    	
    	switch (item.getItemId()) {
    		
    	case MENU_FIND:
    		showDialog(DIALOG_SEARCH);
    		break;
        }
        return super.onOptionsItemSelected(item);
    }
	
    @Override
    protected Dialog onCreateDialog(int id) {
        
    	switch (id) {
	    	case DIALOG_WELCOME:
	    		
	    		LayoutInflater factory1 = LayoutInflater.from(this);
	    		final View textEntryView1 = factory1.inflate(R.layout.copiagenda_welcome, null);
	    		
	    		ImageView logo = (ImageView)textEntryView1.findViewById(R.id.imgPop_up3Logo);
	    		logo.setImageResource(R.drawable.combo);
	    		
		        return new AlertDialog.Builder(this)	        
		        .setTitle("Welcome!")
		        .setView(textEntryView1)
		        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            	showDialog(DIALOG_SEARCH);
		                /* User clicked OK so do some stuff */
		            }
		        })
		        .create();
		    
	    	case DIALOG_SEARCH:
	    		
	    		LayoutInflater factory3 = LayoutInflater.from(this);
	    		final View textEntryView3 = factory3.inflate(R.layout.copiagenda_search, null);
	    		
	    		ImageView movistar = (ImageView) textEntryView3.findViewById(R.id.imgCopiagendaLogo);
	    		movistar.setImageResource(R.drawable.combo);
	    		
		        return new AlertDialog.Builder(this)	        
		        .setTitle("Copiagenda")
		        .setView(textEntryView3)
		        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            	/*
		        	    SharedPreferences sharedPreferences = 
		        	    	PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		        	    
		            	String user = sharedPreferences.getString(LGS_Preferences.KEY_MOVISTAR_USER, "");
		            	String pwd = sharedPreferences.getString(LGS_Preferences.KEY_MOVISTAR_PASSWORD, "");
		            	*/
		            	
		            	String user = OMFManager.getPhone();
		            	String pwd = OMFManager.getMovPwd();
		            	
		            	EditText tcontact_name = (EditText) textEntryView3.findViewById(R.id.namecopiagenda_single);
		            	String contact_name = tcontact_name.getText().toString();
		            	
		            	CheckBox cb = (CheckBox)textEntryView3.findViewById(R.id.cbxcopiagenda);
		            	
		            	if(user==null || pwd==null){
		        			Toast.makeText(getBaseContext(), 
		                            "Please, insert data in main Movistar tab.", 
		                            Toast.LENGTH_LONG).show();
		        			return;
		        		}
		            	
		            	if(user.equals("") || pwd.equals("")){
		        			Toast.makeText(getBaseContext(), 
		                            "Please, insert data in main Movistar tab.", 
		                            Toast.LENGTH_LONG).show();
		        			return;
		        		}
		            	
		            	Copiagenda contacts = new Copiagenda();
		        		contactlist = contacts.RetrieveContacts(user, pwd);
		        		
		        		if(!cb.isChecked())
		        			contactlist = contacts.SearchByName(contact_name, contactlist);
		        		
		        		if(contactlist==null){
		        			Toast.makeText(getBaseContext(), 
		                            "Unable to find the contact list", 
		                            Toast.LENGTH_LONG).show();
		        			return;
		        		}
		        		
		        		if(contactlist.size()==0){
		        			Toast.makeText(getBaseContext(), 
		                            "No contacts available", 
		                            Toast.LENGTH_LONG).show();
		        			return;
		        		}
		        		
		        		mAdapter = new CopiagendaAdapter(PhonesList.this);
		                setListAdapter(mAdapter);
		                /* User clicked OK so do some stuff */
		            }
		        })
		        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            	
		            }
		        })
		        .create();
    	}
    	
    	return null;
    }
    
	public static class CopiagendaAdapter extends BaseAdapter {

		private Context mContext;
		
		public CopiagendaAdapter(Context c) {
            mContext = c;
        }

		public int getCount() {
			// TODO Auto-generated method stub
			return PhonesList.getList().size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view;
			
	        if (convertView == null) {
	            // Make up a new view
	            LayoutInflater inflater = (LayoutInflater) mContext
	                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.copiagenda_list, null);
	        } else {
	            // Use convertView if it is available
	            view = convertView;
	        }
			
	        String contact = PhonesList.getList().get(position);
	        
	        if (!contact.equals(""))
	        {

		        ImageView img = (ImageView) view.findViewById(R.id.copiagenda_image);
		        
				img.setImageResource(R.drawable.user_48);
				
				TextView t = (TextView) view.findViewById(R.id.copiagenda_contact);
				t.setText(contact.replaceAll("\"", "").split(",")[3]);
				
				t = (TextView) view.findViewById(R.id.copiagenda_phone);
				t.setText(contact.replaceAll("\"", "").split(",")[18]);
		        
				return view; 	
	        }
	        
	        return null;
		}

	}
    
}